<template>
  <div class="business-detail">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="back" @click="router.back()">
        <van-icon name="arrow-left" />
      </div>
      <div class="title">商家信息</div>
    </div>

    <!-- 顶部商家信息 -->
    <div class="business-info">
      <div class="business-header">
        <div class="business-img">
          <img :src="business.businessImg" :alt="business.businessName" />
        </div>
        <div class="business-content">
          <div class="business-name">{{ business.businessName }}</div>
          <div class="business-desc">{{ business.businessExplain }}</div>
          <div class="business-address">{{ business.businessAddress }}</div>
          <div class="business-data">
            <span class="delivery-price">配送费¥{{ business.deliveryPrice }}</span>
            <span class="divider">|</span>
            <span class="min-price">起送¥{{ business.starPrice }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 商家公告 -->
    <div class="business-notice" v-if="business.remarks">
      <div class="notice-title">商家公告</div>
      <div class="notice-content">{{ business.remarks }}</div>
    </div>

    <!-- 商品列表 -->
    <div class="food-list">
      <div class="food-item" v-for="food in foodList" :key="food.foodId">
        <div class="food-img">
          <img :src="food.foodImg" :alt="food.foodName" />
        </div>
        <div class="food-content">
          <div class="food-name">{{ food.foodName }}</div>
          <div class="food-desc">{{ food.foodExplain }}</div>
          <div class="food-price">¥{{ food.foodPrice }}</div>
          <div class="food-btns">
            <div class="minus-btn" @click="minusFood(food)">-</div>
            <div class="food-num">{{ food.num || 0 }}</div>
            <div class="plus-btn" @click="addFood(food)">+</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部购物车 -->
    <div class="cart-bar">
      <div class="cart-content">
        <div class="cart-icon">
          <van-icon name="shopping-cart-o" />
          <div class="cart-num" v-if="totalNum > 0">{{ totalNum }}</div>
        </div>
        <div class="cart-info">
          <div class="total-price">¥{{ totalPrice }}</div>
          <div class="delivery-price">配送费¥{{ business.deliveryPrice }}</div>
        </div>
      </div>
      <div class="submit-btn" :class="{'active': totalPrice >= business.starPrice}" @click="submit">
        {{ totalPrice >= business.starPrice ? '去结算' : `还差¥${business.starPrice - totalPrice}起送` }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const business = ref({})
const foodList = ref([])
const userId = ref(null)

// 获取当前用户ID
const getCurrentUserId = () => {
  const userInfo = localStorage.getItem('userInfo')
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo)
      // 确保 userId 是数字类型
      userId.value = Number(user.userId)
      return userId.value && !isNaN(userId.value)
    } catch (error) {
      console.error('解析用户信息失败:', error)
      return false
    }
  }
  return false
}

// 获取商家详情和商品列表
onMounted(async () => {
  const businessId = route.query.businessId
  try {
    // 获取商家详情
    const businessRes = await request.get(`/business/getBusinessById?businessId=${businessId}`)
    if(businessRes.data.code === 200) {
      business.value = {
        ...businessRes.data.data,
        businessImg: `data:image/png;base64,${businessRes.data.data.businessImg.split('base64,')[1]}`
      }
    }
    
    // 获取商品列表
    const foodRes = await request.get(`/food/listFoodByBusinessId?businessId=${businessId}`)
    if(foodRes.data.code === 200) {
      foodList.value = foodRes.data.data.map(food => ({
        ...food,
        foodImg: `data:image/png;base64,${food.foodImg.split('base64,')[1]}`,
        num: 0
      }))
      
      // 如果用户已登录，获取购物车信息
      if (getCurrentUserId()) {
        // 获取购物车列表
        const cartRes = await request.get(`/cart/listCart?userId=${userId.value}&businessId=${businessId}`)
        if (cartRes.data.code === 200) {
          // 更新商品数量
          foodList.value.forEach(food => {
            const cartItem = cartRes.data.data.find(item => item.foodId === food.foodId)
            if (cartItem) {
              food.num = cartItem.quantity
            }
          })
          // 更新总价和总数量
          updateTotalPrice()
        }
      }
    }
  } catch(error) {
    console.error('获取数据失败:', error) 
  }
})

// 更新总价和总数量
const updateTotalPrice = () => {
  let total = 0
  let count = 0
  foodList.value.forEach(food => {
    if (food.num) {
      total += food.num * food.foodPrice
      count += food.num
    }
  })
  totalPrice.value = total
  totalNum.value = count
}

// 修改计算属性为普通的响应式数据
const totalPrice = ref(0)
const totalNum = ref(0)

// 添加商品到购物车
const addFood = (food) => {
  if (!getCurrentUserId()) {
    router.push('/login')
    return
  }

  // 只在本地更新数量
  food.num = (food.num || 0) + 1
  updateTotalPrice()
}

// 减少商品
const minusFood = (food) => {
  if (!getCurrentUserId()) {
    router.push('/login')
    return
  }

  if (!food.num) return

  // 只在本地更新数量
  food.num--
  updateTotalPrice()
}

// 提交订单
const submit = async () => {
  // 检查是否有token
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
    return
  }
  
  if (totalPrice.value < business.value.starPrice) {
    return
  }

  try {
    // 过滤出数量大于0的商品
    const cartItems = foodList.value.filter(food => food.num > 0)
    
    // 遍历处理每个商品
    for (const food of cartItems) {
      try {
        // 1. 先创建购物车项
        await request.post('/cart/saveCart', null, {
          params: {
            userId: userId.value,
            businessId: route.query.businessId,
            foodId: food.foodId
          }
        })

        // 2. 再更新数量
        await request.put('/cart/updateCart', null, {
          params: {
            userId: userId.value,
            businessId: route.query.businessId,
            foodId: food.foodId,
            quantity: food.num
          }
        })
      } catch (error) {
        console.error(`处理商品 ${food.foodName} 失败:`, error)
        showToast(`处理商品 ${food.foodName} 失败`)
        return
      }
    }

    // 所有商品处理成功后，跳转到确认订单页面
    router.push({
      name: 'order-confirm',
      query: {
        businessId: route.query.businessId
      }
    })
  } catch (error) {
    console.error('更新购物车失败:', error)
    showToast('更新购物车失败，请重试')
  }
}
</script>

<style scoped>
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
}

.back {
  font-size: 20px;
  padding: 8px;
  margin-left: -8px;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.business-detail {
  padding-top: 44px;
  min-height: 100vh;
  background: #f5f5f5;
}

.business-info {
  background: #fff;
  padding: 16px;
}

.business-header {
  display: flex;
}

.business-img {
  width: 80px;
  height: 80px;
  margin-right: 12px;
}

.business-img img {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.business-content {
  flex: 1;
}

.business-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.business-desc {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
}

.business-address {
  font-size: 13px;
  color: #999;
  margin-bottom: 8px;
}

.business-data {
  font-size: 13px;
  color: #666;
}

.divider {
  margin: 0 8px;
  color: #ddd;
}

.business-notice {
  margin-top: 12px;
  background: #fff;
  padding: 16px;
}

.notice-title {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.notice-content {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.food-list {
  margin-top: 12px;
  background: #fff;
}

.food-item {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.food-img {
  width: 80px;
  height: 80px;
  margin-right: 12px;
}

.food-img img {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.food-content {
  flex: 1;
  position: relative;
}

.food-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.food-desc {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
}

.food-price {
  font-size: 16px;
  color: #f60;
  font-weight: bold;
}

.food-btns {
  position: absolute;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
}

.minus-btn,
.plus-btn {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  cursor: pointer;
}

.food-num {
  margin: 0 12px;
  font-size: 16px;
  color: #333;
}

.cart-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 50px;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.cart-content {
  flex: 1;
  display: flex;
  align-items: center;
}

.cart-icon {
  position: relative;
  margin-right: 12px;
}

.cart-icon .van-icon {
  font-size: 24px;
  color: #666;
}

.cart-num {
  position: absolute;
  top: -8px;
  right: -8px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  background: #f60;
  color: #fff;
  border-radius: 8px;
  font-size: 12px;
  padding: 0 4px;
}

.cart-info {
  flex: 1;
}

.total-price {
  font-size: 18px;
  color: #f60;
  font-weight: bold;
}

.delivery-price {
  font-size: 12px;
  color: #999;
}

.submit-btn {
  width: 100px;
  height: 36px;
  background: #ccc;
  color: #fff;
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 12px;
  font-size: 14px;
}

.submit-btn.active {
  background: #0097ff;
  cursor: pointer;
}
</style> 